package com.pinyoumei.app.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.wallet.WalletRechargeActivity;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.event.AlipayEvent;
import com.pinyoumei.app.view.StatusBarHeightView;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2020-04-24.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2020-04-24        Administrator             新增Person类
 * 2020-04-24        Administrator             增加sex属性
 */
public class WebViewActivity extends BaseActivity {
    private StatusBarHeightView height_view;
    private RelativeLayout rl_1;
    private RelativeLayout relative_finish;
    private TextView text_title;
    private BridgeWebView webView;

    private String url = "";
    private String order_title = "";

    private ValueCallback<Uri> mUploadMessage;

    private ValueCallback<Uri[]> mUploadMessageArray;
    int RESULT_CODE = 0;
    private FrameLayout flVideoContainer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE|
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
//        AndroidBug5497Workaround.assistActivity(this);
        url = getIntent().getStringExtra("url");
        order_title = getIntent().getStringExtra("order_title");

        height_view = findViewById(R.id.height_view);
        rl_1 = findViewById(R.id.rl_1);
        text_title = findViewById(R.id.text_title);
        relative_finish = findViewById(R.id.relative_finish);
        relative_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        webView = findViewById(R.id.webview);
        flVideoContainer = findViewById(R.id.flVideoContainer);




        webView.setWebChromeClient(new WebChromeClient());
        // 设置具体WebViewClient
        webView.setWebViewClient(new WebViewActivity.MyWebViewClient(webView));
        // set HadlerCallBack
        webView.setDefaultHandler(new WebViewActivity.myHadlerCallBack());


        // setWebChromeClient
        webView.setWebChromeClient(new WebChromeClient() {
            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
                this.openFileChooser(uploadMsg);
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
                this.openFileChooser(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                pickFile();
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mUploadMessageArray = filePathCallback;
                pickFile();
                return true;
            }







            CustomViewCallback mCallback;
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {

                fullScreen();

                webView.setVisibility(View.GONE);
                flVideoContainer.setVisibility(View.VISIBLE);
                flVideoContainer.addView(view);
                mCallback = callback;
                super.onShowCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {

                fullScreen();

                webView.setVisibility(View.VISIBLE);
                flVideoContainer.setVisibility(View.GONE);
                flVideoContainer.removeAllViews();
                super.onHideCustomView();

            }

        });


//        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        WebSettings webSettings = webView.getSettings();
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheMaxSize(1024*1024*8);//存储的最大容量
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);



        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M  && url.contains("#new")) {
            //小于6.0
            Intent intent = new Intent();
            intent.setAction( "android.intent.action.VIEW");
            Uri content_url = Uri. parse(url);
            intent.setData(content_url);
            startActivity(intent);
            finish();
        } else {

            webView.loadUrl(url);


        }







        if (order_title!=null){
            height_view.setVisibility(View.VISIBLE);
            rl_1.setVisibility(View.VISIBLE);
            text_title.setText(order_title);
        }



    }


    class MyWebViewClient extends BridgeWebViewClient {

        private String mReffer;

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

        // Handle API 21+
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            ///获取请求uir
            String url = request.getUrl().toString();
            ///获取RequestHeader中的所有 key value
            Map<String, String> lRequestHeaders = request.getRequestHeaders();
//            LogUtils.e("测试URI"+url);
//            for (Map.Entry<String, String> lStringStringEntry : lRequestHeaders.entrySet()) {
//                LogUtils.e("测试header"+lStringStringEntry.getKey() + "  " + lStringStringEntry.getValue());
//            }
            if (lRequestHeaders.containsKey("Referer")) {
                mReffer = lRequestHeaders.get("Referer");
            }
            return super.shouldInterceptRequest(view, request);
        }


        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url){
            if (url.startsWith("weixin://wap/pay?") || url.startsWith("http://weixin/wap/pay") ) {
                try {
                    startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    return true;
                } catch (Exception e) {

                }
                return  true;
            } else {
                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Referer", "https://www.ugali.cn");
                if (url.contains("alipays:") || url.contains("alipay")) {
                 /**
                 * 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次
                 */
                final PayTask task = new PayTask(WebViewActivity.this);
               task.payInterceptorWithUrl(url, true, new H5PayCallback() {
                    @Override
                    public void onPayResult(final H5PayResultModel result) {
                        // 支付结果返回
                        final String url = result.getReturnUrl();
                        if (!TextUtils.isEmpty(url)) {
                            WebViewActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    view.loadUrl(url);
                                }
                            });
                        }

                        // 5000支付失败 6001重复请求 6002中途取消
                        if ("5000".equals(result.getResultCode()) || "6001".equals(result.getResultCode()) ||
                                "6002".equals(result.getResultCode())){
                            ToastUtils.showShort("支付失败");
                            finish();
                        }else{
                            EventBusUtils.postSticky(new AlipayEvent("1"));
                            ToastUtils.showShort("支付成功");
                            finish();
                        }
                    }
                });

                } else {
                    if ( !url.contains("pinduoduo") && !url.contains("youku://")){
                        view.loadUrl(url, extraHeaders);
                    }

                }







            }
            // ------- 处理结束 -------
            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true;
            }
            return true;
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            loadingDailog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            loadingDailog.dismiss();

        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            // 不要使用super，因为包含了一条 handler.cancel(), 去掉super 解决了白屏的问题
            // super.onReceivedSslError(view, handler, error);
            // 接受所有网站的证书，忽略SSL错误，执行访问网页
            handler.proceed();
        }

    }

    /**
     * 自定义回调（web端发送数据给安卓）
     */
    class myHadlerCallBack extends DefaultHandler {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (function != null) {
                Toast.makeText(WebViewActivity.this, data, Toast.LENGTH_SHORT).show();
            }
        }
    }



    public void pickFile() {
        Intent chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
        chooserIntent.setType("image/*");
        startActivityForResult(chooserIntent, RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == RESULT_CODE) {
            if (null == mUploadMessage && null == mUploadMessageArray){
                return;
            }
            if(null!= mUploadMessage && null == mUploadMessageArray){
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }

            if(null == mUploadMessage && null != mUploadMessageArray){
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                if (result != null) {
                    mUploadMessageArray.onReceiveValue(new Uri[]{result});
                }
                mUploadMessageArray = null;
            }

        }
    }



    private void fullScreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }
    }

    @Override
    public boolean
    onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();//返回上个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);//退出baiH5界面
    }




    @Override
    public void onPause() {
        super.onPause();
        webView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        webView.onResume();
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView!=null){
            webView.destroy();
        }

    }




}
